<template>
  <div>
    <div class="body">
      <mavon-editor v-model="editor.articleContent"
                    ref="md"
                    @change="editorChange"
                    @imgAdd="imgAdd"
                    class="editorCss"
                    @imgDel="imgDel"
                    placeholder="开始编写... 删除内容将不会保存"
                    :toolbars="toolbars"
      >
      </mavon-editor>
    </div>
    <div class="bottom-tool">
      文章标题：
      <el-input minlength="3" v-model="editor.articleTitle" style="width: 60%"/>
      &nbsp
      <el-button type="success" @click="sub" plain>提交文章</el-button>
      <el-button type="danger" @click="resetAll">重置所有</el-button>
    </div>

    <el-dialog :visible.sync="dialogVisible">
      <template slot="title">
        <h4>提交文章</h4>
      </template>
      <div>
        <table class="submitTableCss">
          <tr>
            <td>
              文章分类：
              <el-select
                  v-model="editor.categoryName"
                  filterable
                  allow-create
                  default-first-option
                  style="width: 300px"
                  placeholder="请选择文章分类，可以输入自己的分类">
                <el-option
                    v-for="item in categories"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </td>
          </tr>
          <tr>
            <td>
              <el-radio-group v-model="editor.isPrivate">
                <el-radio :label="0">公开</el-radio>
                <el-radio :label="1">私有</el-radio>
              </el-radio-group>
            </td>
          </tr>
        </table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" @click="saveDraft" plain>保存草稿</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="danger" plain @click="submitArticle">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as imageConversion from 'image-conversion';

export default {
  methods: {
    saveDraft() {
      this.editor.isDraft = 1
      this.submitArticle()
    },
    submitArticle() {
      if (this.editor.categoryName == "") {
        this.commonUtil.hintMessage("文章分类不能为空")
        return
      }
      if (this.editor.articleTitle == "") {
        this.commonUtil.hintMessage("文章标题不能为空")
        return
      }
      this.dialogVisible = false
      this.postRequest(this.api.article, this.editor).then(res => {
        if (res) {
          this.$message.success(res.message)
        }
      })
    },
    resetAll() {
      this.editor = {
        articleTitle: new Date().toLocaleString(),
        articleContent: "",
        isDraft: 0,
        isPrivate: 0,
        categoryName: ""
      }
    },
    sub() {
      if (this.editor.articleContent == "") {
        this.commonUtil.hintMessage("没有文章内容")
        return
      }
      this.dialogVisible = true
    },
    //参数1 markdown语法 2 html语法
    editorChange(value, render) {
      this.editor.articleContent = value
    },
    imgAdd(pos, $file) {
      //新建form表单类型的数据
      let formData = new FormData();
      if ($file.size / 1024 < this.config.UPLOAD_SIZE) {
        formData.append("file", $file);
        this.axios({
          url: this.api.article + "img",
          method: "POST",
          data: formData,
          headers: {"Content-Type": "multipart/form-data"},
        }).then((res) => {
          if (res) {
            // 将后端返回的url放在md中图片的指定位置
            this.$refs.md.$img2Url(pos, res.data);
          }
        });
      } else {
        imageConversion.compressAccurately($file, this.config.UPLOAD_SIZE).then(res => {
          let f = new File([res], $file.name, { type: $file.type })
          formData.append("file",f)
          this.axios({
            url: this.api.article + "img",
            method: "POST",
            data: formData,
            headers: {"Content-Type": "multipart/form-data"},
          }).then((res) => {
            if (res) {
              // 将后端返回的url放在md中图片的指定位置
              this.$refs.md.$img2Url(pos, res.data);
            }
          });
        });
      }
    },
    imgDel(e) {
    }
  },
  mounted() {
    let tempArticle = sessionStorage.getItem("article")
    if (tempArticle != null) {
      this.editor = JSON.parse(tempArticle)
    }
    window.addEventListener('beforeunload', () => {
      if (this.editor.articleContent != "") {
        sessionStorage.setItem("article", JSON.stringify(this.editor))
      } else {
        sessionStorage.removeItem("article")
      }
    })
  },
  destroyed() {
    if (this.editor.articleContent != "") {
      sessionStorage.setItem("article", JSON.stringify(this.editor))
    } else {
      sessionStorage.removeItem("article")
    }
    window.removeEventListener('beforeunload', () => {
    })
  },
  data() {
    return {
      config: {
        UPLOAD_SIZE: 300,
      },
      dialogVisible: false,
      editor: {
        articleTitle: new Date().toLocaleString(),
        articleContent: "",
        isDraft: 0,
        isPrivate: 0,
        categoryName: ""
      },
      categories: [
        {
          label: "java",
          value: "java"
        },
        {
          label: "sql",
          value: "sql"
        },
        {
          label: "项目经历",
          value: "项目经历"
        },
        {
          label: "随笔",
          value: "随笔"
        }
      ],
      toolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: true, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true, // 预览
      }
    }
  },
}
</script>

<style scoped>
.submitTableCss {
  border-spacing: 20px;
  width: 100%;
}

.bottom-tool {
  width: 100%;
  margin: 1vh;
}

.body {
  height: 82vh;
  border: 2px black solid;
  /*border-radius: 10px;*/
}

.editorCss {
  height: 82vh;
}
</style>